package com.zjitc.model;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;

/**
 * Create by IntelliJ IDEA
 *
 * @author: lhl
 * @date-Time: 2018/4/5 0005
 * @description:
 */
public class History {

    private static final int MAX_HISTORY_SIZE = 8;
    private Map<String, Product> products = new HashMap<>();
    Queue<String> keys = new LinkedList<>();

    public History() {
    }

    public History(Map<String, Product> products) {

        this.products = products;
    }

    public Map<String, Product> getProducts() {
        return products;
    }

    public void setProducts(Map<String, Product> products) {
        this.products = products;
    }

    /**
     * 每次浏览的时候， 1. 向该类中添加商品，如果商品已经存在了， 不用添加，如果商品不存在，则添加， 2. 只保存8个数据
     */
    public void add(Product product) {
        String pid = product.getPid();
        if (products.containsKey(pid)) {
            return;
        }

        products.put(pid, product);
        keys.add(pid);

        while (keys.size() >= MAX_HISTORY_SIZE) {
            String key = keys.poll();
            products.remove(key);
        }
    }

    public void clear() {
        products.clear();
    }
}
